package com.huxb.contentcenter.controller;

import com.huxb.contentcenter.domain.dto.UserDTO;
import com.huxb.contentcenter.domain.vo.ShareVo;
import com.huxb.contentcenter.entity.share.Share;
import com.huxb.contentcenter.service.ShareService;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author huxb
 * @date 2020/2/8 0008 下午 4:31
 */
@RequestMapping("/shares")
@RestController
public class ShareController {

    @Autowired
    private ShareService shareService;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/{id}")
    public Object findShareById(@PathVariable("id") Integer id) {
        Share share = shareService.findShareById(id);
        Integer userId = share.getUserId();

        List<ServiceInstance> userInstance = discoveryClient.getInstances("user-center");
        String host = userInstance.get(0).getHost();
        Integer port = userInstance.get(0).getPort();
        String uri =  String.valueOf(userInstance.get(0).getUri()) ;
        UserDTO userDTO = restTemplate.getForObject(uri + "/users/{id}", UserDTO.class, userId);

        ShareVo shareVo = new ShareVo();
        BeanUtils.copyProperties(share, shareVo);
        shareVo.setWxNickname(userDTO.getWxNickname());
        return  shareVo;
    }
}
